<template>
	<view>
		订单编号：{{order.order_no}}
	</view>

	<view>
		订单金额：{{order.total}}
	</view>

	<view class="btm">

		<view class="btn" @click="pay">确认支付</view>

	</view>

	<!--插入支付html-->
	<div ref="htmlContainer"></div>
</template>

<script setup>
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		queryDetail
	} from '@/api/order.js'
	import {
		ref
	} from 'vue'
	import {
		toPay
	} from '@/api/pay.js'

	//订单数据
	const order = ref({});
	//同名引用  
	const htmlContainer = ref(null);

	//查询
	async function init(no) {
		let res = await queryDetail(no);
		if (res.code == 200) {
			order.value = res.data;
		}
	}

	//支付 
	async function pay() {
		let data = {
			payType: 1,
			userId: 23,
		};
		data.payAmount = 360;
		data.orderIds = order.value.order_no;

		let res = await toPay(data);
		if (res.code == 200) {
			//获取html脚本 
			let tmp = res.data.alipayResult;
			renderHtmlWithJs(tmp);

		}
	}

	// 渲染包含JS的HTML内容
	function renderHtmlWithJs(html) {
		if (!htmlContainer.value) return;

		// 先清空容器
		htmlContainer.value.innerHTML = '';

		// 创建一个临时容器来解析HTML
		const tempDiv = document.createElement('view');
		tempDiv.innerHTML = html;

		// 将解析后的内容添加到目标容器
		while (tempDiv.firstChild) {
			htmlContainer.value.appendChild(tempDiv.firstChild);
		}

		// 执行所有脚本标签
		executeScriptsInElement(htmlContainer.value);
	}

	function executeScriptsInElement(element) {
		// 获取所有脚本标签
		const scripts = element.querySelectorAll('script');

		scripts.forEach(oldScript => {
			// 创建新的脚本标签
			const newScript = document.createElement('script');

			// 复制属性
			Array.from(oldScript.attributes).forEach(attr => {
				newScript.setAttribute(attr.name, attr.value);
			});

			// 复制内容
			const scriptText = document.createTextNode(oldScript.innerHTML);
			newScript.appendChild(scriptText);

			// 替换旧脚本标签
			oldScript.parentNode.replaceChild(newScript, oldScript);

		});
	}


	//页面加载完成
	onLoad(data => {
		init(data.no);
	})
</script>

<style scoped>
	.btn {
		width: 700rpx;
		background-color: #d81e06;
		height: 60rpx;
		line-height: 60rpx;
		color: #fff;
		border-radius: 50px;
		margin: auto;
		text-align: center;
	}

	.btm {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 750rpx;
		height: 100rpx;
		background-color: #fff;
	}
</style>
